package org.sys.transporttrainsys.service;

import org.sys.transporttrainsys.dto.ExamStatistics;
import org.sys.transporttrainsys.entity.StudentExamStatus;
import org.sys.transporttrainsys.repository.StudentExamStatusRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentExamStatusService {

    @Autowired
    private StudentExamStatusRepository repository;

    public List<StudentExamStatus> getAllExamStatuses() {
        return repository.findAll(); // 获取所有学员考试情况
    }

    public List<StudentExamStatus> getByStudentId(Long studentId) {
        return repository.findByStudentId(studentId); // 根据学员ID查询
    }

    public List<StudentExamStatus> getByExamId(Long examId) {
        return repository.findByExamId(examId); // 根据考试ID查询
    }

    // 其他统计分析方法可以在这里添加
    // 统计分析功能
    // 统计分析功能
    public List<ExamStatistics> getStatistics() {
        List<StudentExamStatus> statuses = repository.findAll();

        // 按考试分组
        Map<Long, List<StudentExamStatus>> groupedByExam = statuses.stream()
                .collect(Collectors.groupingBy(status -> status.getExam().getId()));

        return groupedByExam.values().stream()
                .map(examStatuses -> {
                    long examId = examStatuses.get(0).getExam().getId();
                    String examName = examStatuses.get(0).getExam().getName();
                    double averageScore = examStatuses.stream()
                            .mapToInt(StudentExamStatus::getExamRecordScore)
                            .average().orElse(0);
                    long passedCount = examStatuses.stream()
                            .filter(status -> "通过".equals(status.getResult()))
                            .count();
                    int totalAttempts = examStatuses.size();
                    double passRate = totalAttempts > 0 ? (double) passedCount / totalAttempts * 100 : 0;

                    return new ExamStatistics(examId, examName, averageScore, passRate, totalAttempts, (int) passedCount);
                })
                .collect(Collectors.toList());
    }
}
